const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}
/**
   * 获取数字的小数位数
   */
  const getDecimalDigits = (num) => {
    const str = num.toString();
    if (str.includes('e-')) {
      // 处理科学计数法
      return parseInt(str.split('e-')[1], 10);
    }
    const decimalPart = str.split('.')[1];
    return decimalPart ? decimalPart.length : 0;
  }

  /**
   * 将数字转换为整数（用于高精度计算）
   * 返回：{ value: 转换后的整数值, factor: 转换因子 }
   */
  const toInteger = (num) => {
    if(num === undefined){
        return 0;
    }
    const digits = getDecimalDigits(num);
    const factor = Math.pow(10, digits);
    return {
      value: Math.round(num * factor),
      factor
    };
  }

  /**
   * 加法
   */
  const add = (a, b) => {
    const { value: aInt, factor: aFactor } = toInteger(a);
    const { value: bInt, factor: bFactor } = toInteger(b);
    
    // 统一因子
    const commonFactor = Math.max(aFactor, bFactor);
    const aScaled = aInt * (commonFactor / aFactor);
    const bScaled = bInt * (commonFactor / bFactor);
    
    // 计算结果并还原
    return (aScaled + bScaled) / commonFactor;
  }

  /**
   * 减法
   */
  const subtract = (a, b) => {
    return this.add(a, -b);
  }

  /**
   * 乘法
   */
  const multiply = (a, b) => {
    const { value: aInt, factor: aFactor } = toInteger(a);
    const { value: bInt, factor: bFactor } = toInteger(b);
    return (aInt * bInt) / (aFactor * bFactor);
  }

  /**
   * 除法
   */
  const divide = (a, b) => {
    if (b === 0) throw new Error("除数不能为零");
    
    const { value: aInt, factor: aFactor } =toInteger(a);
    const { value: bInt, factor: bFactor } = toInteger(b);
    
    // 扩大被除数，提高精度
    const scaledDividend = aInt * factor;
    return (scaledDividend / bInt) / (aFactor * factor / bFactor);
  }
// 列表转tree (parentId、id)
const listToTree = list => { 
    const nodeMap = new Map(); // 创建一个映射 (map)，以便快速查找每个节点 
    const result = [];  // 存储所有的根节点
    // 第一次遍历，建立映射关系和初始化 children 属性
    list.forEach(node => {
        node.children = []; // 确保每个节点都有 children 属性
        nodeMap.set(node.id, node);
    });
    // 第二次遍历，构建父子关系
    list.forEach(node => {
        if (node.parentId == 0) {  // 如果 parentId 是 0，则认为是根节点，加入结果数组
            result.push(node); 
        } else { // 非根节点，找到其父节点并添加到父节点的 children 数组中
            const parent = nodeMap.get(node.parentId);
            if (parent) {
                parent.children.push(node);
            }
        }
    }); 
    return result;
}
/**
 * 处理aef 物料分类tree 的元数据 （接口返回是列表数据
 * 重新获取tree 分级数组 [{"name":"一级"}],[{"name":"二级"}]  
 * @param {*} IndexArr 
 * @param {*} Tree 
 * @returns 
 */ 
const opAefMetaCateMeta = (IndexArr, Tree) => { 
  let meta = [];
  let level = 1;
  for (let index = 0; index < IndexArr.length; index++) {
    if (level == 1) {
      meta[index] = Tree;
    } else if (level == 2) {
      meta[index] = Tree[IndexArr[index - 1]].children;
    } else if (level == 3) {
      meta[index] =
        Tree[IndexArr[index - 2]].children[IndexArr[index - 1]].children;
    }
    level++;
  }
  return meta;
}

 
module.exports = {
  formatTime,
  listToTree,
  opAefMetaCateMeta,
  add,
  subtract,
  divide,
  multiply
}
